package cz.cuni.amis.episodic.lisp.behan;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.ListIterator;

class TraceVisitor implements Visitor<ArrayList<String>> {
    public ArrayList<ArrayList<String>> trace;
    public PrintWriter out;

    TraceVisitor(ArrayList<ArrayList<String>> _trace, ArrayList<String> data, PrintWriter fout) {
        if (_trace == null) {
            this.trace = new ArrayList<ArrayList<String>>();
        } else {
            this.trace = new ArrayList<ArrayList<String>>(_trace);
        }

        if (data != null) {
            // Or node
            this.trace.add(data);
            if (!data.get(0).substring(0,1).matches("!")) {
                ArrayList<String> orNode = new ArrayList<String>();
                orNode.add(String.format("AND_%s", data.get(0)));
                this.trace.add(orNode);
            }
        }

        out = fout;
    }

    public Visitor<ArrayList<String>> visitTree(VisitableTree<ArrayList<String>> tree) {
        return new TraceVisitor(trace, tree.showdata(), out);
    }

    public boolean visitData(VisitableTree<ArrayList<String>> parent, ArrayList<String> data, boolean isLeaf) throws java.io.IOException {
        ListIterator<ArrayList<String>> iter = trace.listIterator();

        if (iter.hasNext()) {
            ArrayList<String> elem = iter.next();

            while(iter.hasNext()) {
                dataPrinter.printData(elem, out);
                out.write('-');
                elem = iter.next();
            }
            dataPrinter.printData(elem, out);
            out.write('\n');
        }

        return true;
    }

    public boolean postVisitData(VisitableTree<ArrayList<String>> parent, ArrayList<String> data, boolean isLeaf) throws java.io.IOException {
        visitData(parent, data, isLeaf);
        return true;
    }
}